import { Component, OnInit, Output, Input, EventEmitter, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { LocalStorage } from '@core/local.storage';
import { ApiService } from '@core/api.service';
import { _HttpClient } from '@delon/theme';
import { DatePipe } from '@angular/common';
import { TreeTools } from '@core/treeTools.tool';
import { EquipmentComponent } from '../../../layout/components/equipment.component';
import { environment } from '../../../../environments/environment';
import { forkJoin } from 'rxjs';

@Component({
    selector: 'app-calendaropera',
    templateUrl: './calendarOpera.component.html',
    styleUrls: ['./workAreaWeave.component.less']
})
export class CalendarOperaComponent implements OnInit {
    @ViewChild('equcom', { static: true }) equcom: EquipmentComponent;
    @Input() apiUrl: any;
    @Input() operaType: any;
    @Input() width: any;
    @Input() responseData: any;
    @Input() popTitle: any;
    @Output() public closeModal = new EventEmitter();
    @Output() public reloadData = new EventEmitter();

    treeNodeStyle = { 'max-width': '350px', 'max-height': '300px', 'overflow-y': 'auto', 'overflow-x': 'hidden' };
    Visible = false;
    operaData: any = {};
    objData: any = {};
    thisData: any = { 'count': 0, 'vcId': [] };
    wxlxTree: any = [];
    operaList: any = [
        { equipmentModal: false }
    ];
    isLoading: any = {};

    chejianValue: any;
    chejianList: any = [];
    gongquIf = true;
    gongquValue: any;
    gongquList: any = [];
    chezhanIf = true;
    chezhanValue: any;
    chezhanList: any = [];

    constructor(
        private msg: NzMessageService,
        public ls: LocalStorage,
        private datePipe: DatePipe,
        private apiService: ApiService,
        public treeTools: TreeTools,
        private http: _HttpClient
    ) { }

    ngOnInit() {
        this.operaData.operaType = this.operaType;
        switch (this.operaType) {
            case 'add':
                this.getApi(() => {
                    this.operaData.dtWorkdate = this.responseData.startStr;
                    this.operaData.vcLevel = '0';
                    this.operaData.vcNeekskywin = '1';
                    this.operaData.vcNeedroad = '1';
                    this.getAllChejian(false, '');
                });
                break;
            case 'edit':
            case 'view':
                this.getApi(() => {
                    // 车间/工区/车站数据还原
                    this.apiService.getAllChejian('1').subscribe((chejian: any) => {
                        if (chejian.length) {
                            for (const item of chejian) {
                                this.chejianList.push({
                                    opValue: !item.opValue ? '0' : item.opValue,
                                    opName: item.opName
                                });
                            }
                            // 没有工区ID就使用车间ID查出工区列表
                            let workarea = this.responseData.vcWsId;
                            if (this.responseData.vcWaId) {
                                workarea = this.responseData.vcWaId;
                            }
                            this.apiService.getgongquByCjId(this.responseData.vcWsId).subscribe((gongqu: any) => {
                                this.gongquIf = true;
                                if (gongqu.length) {
                                    for (const item of gongqu) {
                                        this.gongquList.push({
                                            opValue: !item.opValue ? '0' : item.opValue,
                                            opName: item.opName
                                        });
                                    }
                                    this.apiService.getStationByOrgId(this.responseData.vcWsId, '1').subscribe((chezhan: any) => {
                                        this.chezhanIf = true;
                                        if (chezhan.length) {
                                            for (const item of chezhan) {
                                                this.chezhanList.push({
                                                    opValue: !item.opValue ? '0' : item.opValue,
                                                    opName: item.opName
                                                });
                                            }
                                            this.operaData = this.responseData;
                                            this.operaData.vcStaId = this.responseData.vcStaid;
                                            // 还原作业项目
                                            this.workProjectChange(this.operaData.vcProject);
                                        }
                                    });
                                }
                            });
                        }
                    });
                });
                break;
        }
    }
    getApi(callback) {
        setTimeout(() => {
            this.Visible = true;
            const updateApi = [
                this.http.get(environment.apiBase + '/csmis/jxProjects/getAllJxProjects.jwt')
            ];
            forkJoin(updateApi).subscribe((results: any) => {
                if (results[0]) {
                    this.wxlxTree = this.formatTreeNode(results[0]);
                }
                if (callback) {
                    callback()
                }
            });
        }, 200);
    }
    workProjectChange(event) {
        this.http.get(environment.apiBase + '/csmis/jxProjects/findOne.jwt?id=' + event).subscribe(res => {
            if (res.length) {
                // DEVLEVEL设备等级,DEVTYPE设备类型,LEVELNAME作业等级,TYPENAME作业类型
                this.operaData.typeid = res[0].TYPEID;
                this.operaData.devlevel = res[0].DEVLEVEL;
                this.operaData.vcProjecttype = res[0].TYPENAME;
                this.operaData.devtype = res[0].DEVTYPE;
                this.operaData.vcDevlevel = res[0].DEVTYPELEVEL;
            }
        });
    }
    // 把接口数据转化为zorro树形数据格式
    formatTreeNode(resdata) {
        const node: any = [];
        for (let i = 0; i < resdata.length; i++) {
            if (resdata[i].children) {
                node.push({
                    title: resdata[i].text,
                    key: resdata[i].id,
                    disabled: true,
                    children: []
                });
                for (let j = 0; j < resdata[i].children.length; j++) {
                    if (resdata[i].children[j].children) {
                        node[i].children.push({
                            title: resdata[i].children[j].text,
                            key: resdata[i].children[j].id,
                            disabled: true,
                            children: []
                        });
                        for (const item of resdata[i].children[j].children) {
                            // 三级
                            node[i].children[j].children.push({
                                title: item.text,
                                key: item.id,
                                isLeaf: true
                            });
                        }
                    } else {
                        // 二级
                        node[i].children.push({
                            title: resdata[i].children[j].text,
                            key: resdata[i].children[j].id,
                            isLeaf: true
                        });
                    }
                }
            } else {
                // 一级
                node.push({
                    title: resdata[i].text,
                    key: resdata[i].id,
                    isLeaf: true
                });
            }
        }
        return node;
    }
    // 车间
    getAllChejian(reload, select) {
        this.chejianList = [];
        this.chejianValue = '';

        this.apiService.getAllChejian('1').subscribe((res: any) => {
            if (res.length) {
                for (const item of res) {
                    this.chejianList.push({
                        opValue: !item.opValue ? '0' : item.opValue,
                        opName: item.opName
                    });
                }
                this.chejianValue = reload ? select.chejianValue : this.chejianList[0].opValue;
                this.getgongquByCjId(this.chejianValue, reload, select);
            }
        });
    }
    // 工区
    getgongquByCjId(orgId, reload, select) {
        if (!orgId) {
            return;
        }
        this.gongquIf = false;
        this.gongquList = [];
        this.gongquValue = '';

        this.apiService.getgongquByCjId(orgId).subscribe((res: any) => {
            this.gongquIf = true;
            if (res.length) {
                for (const item of res) {
                    this.gongquList.push({
                        opValue: !item.opValue ? '0' : item.opValue,
                        opName: item.opName
                    });
                }
                this.gongquValue = reload ? select.gongquValue : this.gongquList[0].opValue;
                this.getStationByOrgId(this.gongquValue, reload, select);
            }
        });
    }
    // 车站
    getStationByOrgId(orgId, reload, select) {
        if (!orgId) {
            return;
        }
        this.chezhanIf = false;
        this.chezhanList = [];
        this.chezhanValue = '';

        this.apiService.getStationByOrgId(orgId, '1').subscribe((res: any) => {
            this.chezhanIf = true;
            if (res.length) {
                for (const item of res) {
                    this.chezhanList.push({
                        opValue: !item.opValue ? '0' : item.opValue,
                        opName: item.opName
                    });
                }
                this.chezhanValue = reload ? select.chezhanValue : this.chezhanList[0].opValue;
            }
        });
    }
    chejianChange(e) {
        setTimeout(() => {
            this.getgongquByCjId(e, false, '');
            this.operaData.vcWsId = e;
        }, 500);
    }
    gongquChange(e) {
        setTimeout(() => {
            this.getStationByOrgId(e, false, '');
            this.operaData.vcWaId = e;
        }, 500);
    }
    chezhanChange(e) {
        setTimeout(() => {
            this.operaData.vcStaId = e;
        }, 500);
    }
    devName() {
        if (this.operaData.vcProject && this.operaData.vcStaId) {
            this.modalShow('equipmentModal');
        } else {
            this.msg.error('请先选择作业项目和车站', { nzDuration: 1000 });
        }
    }
    modalShow(type) {
        this.operaList[type] = true;
    }
    modalHide(type) {
        this.operaList[type] = false;
    }
    equipmentValue(e) {
        this.operaData.vcDevname = e.split('++')[0].split('|')[0];
        this.operaData.vcDevid = e.split('++')[0].split('|')[1];

        this.operaData.vcDevgroupname = e.split('++')[1].split('|')[0];
        this.operaData.vcDevgroupid = e.split('++')[1].split('|')[1];
        this.operaData.vcGroupDevName = e.split('++')[1].split('|')[2];
        this.operaData.vcGroupDevId = e.split('++')[1].split('|')[3];
    }
    Ok() {
        if (this.operaType === 'view') {
            this.Visible = false;
            setTimeout(() => {
                this.closeModal.emit();
                this.reloadData.emit();
            }, 200);
            return;
        }
        this.isLoading.Ok = true;
        setTimeout(() => {
            this.isLoading.Ok = false;
        }, 2000);
        const param: any = {};
        switch (this.operaType) {
            case 'add':
            case 'edit':
                if (!this.operaData.vcProject) {
                    this.msg.error('必填项不能为空', { nzDuration: 1000 });
                    return;
                }
                param.vcMid = this.operaData.vcMid;
                param.dtWorkdate = this.datePipe.transform(this.operaData.dtWorkdate, 'yyyy-MM-dd');
                param.vcProjecttype = this.operaData.typeid ? JSON.stringify(this.operaData.typeid) : '';
                param.vcProject = this.operaData.vcProject ? this.operaData.vcProject : '';
                param.vcDevlevel = this.operaData.devlevel ? this.operaData.devlevel : '';
                // 设备组有设备name和id使用设备组的
                if (this.operaData.vcGroupDevId && this.operaData.vcGroupDevId.split(',').length) {
                    param.vcDevname = this.operaData.vcGroupDevName ? this.operaData.vcGroupDevName : '';
                    param.vcDevid = this.operaData.vcGroupDevId ? this.operaData.vcGroupDevId : '';
                } else {
                    param.vcDevname = this.operaData.vcDevname ? this.operaData.vcDevname : '';
                    param.vcDevid = this.operaData.vcDevid ? this.operaData.vcDevid : '';
                }
                param.vcDevGroupName = this.operaData.vcDevgroupname ? this.operaData.vcDevgroupname : '';
                param.vcDevGroupId = this.operaData.vcDevgroupid ? this.operaData.vcDevgroupid : '';

                param.vcLevel = this.operaData.vcLevel ? this.operaData.vcLevel : '';
                param.vcNeekskywin = this.operaData.vcNeekskywin;
                param.vcNeedroad = this.operaData.vcNeedroad;
                param.vcWsId = this.operaData.vcWsId ? this.operaData.vcWsId : '';
                param.vcWaId = this.operaData.vcWaId ? this.operaData.vcWaId : '';
                param.vcStaid = this.operaData.vcStaId ? this.operaData.vcStaId : '';
                if (this.operaType === 'edit') {
                    param.vcId = JSON.stringify(this.operaData.vcId);
                }
                break;
        }
        this.http.post(this.apiUrl, param).subscribe((res: any) => {
            if (!res.code) {
                this.Visible = false;
                setTimeout(() => {
                    this.closeModal.emit();
                    this.reloadData.emit();
                }, 200);
            } else {
                if (res.msg) {
                    this.msg.error(res.msg);
                } else {
                    this.msg.error('操作失败');
                }
            }
        });
    }
    Cancel() {
        this.Visible = false;
        setTimeout(() => {
            this.closeModal.emit();
        }, 200);
    }
}
